package com.labtalk.admin.config.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.labtalk.admin.constant.HttpStatus;
import com.labtalk.admin.pojo.common.ResponseVo;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author G-pointy
 * @Date 2022/8/10
 * @Description: 自定义权限不足 配置类
 */
@Component
public class RestAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        ResponseVo responseCommon = ResponseVo.error(HttpStatus.FORBIDDEN, "权限不足，请联系管理员", null);
        out.write(new ObjectMapper().writeValueAsString(responseCommon));
        out.flush();
        out.close();
    }
}
